package ez

import (
	"encoding/json"
	"fmt"
	"os"
)

type ServiceInfo struct {
	Service *ServiceConfig
	Server  *ServerConfig
	Pid     int
	RunPath string
}

func (i *ServiceInfo) ToBytes() []byte {
	data, e := json.Marshal(i)
	if e != nil {
		LogToConsole(e.Error())
		return nil
	}
	return data
}
func CreatInfoFromBytes(data []byte) *ServiceInfo {
	info := &ServiceInfo{}
	e := json.Unmarshal(data, info)
	if e != nil {
		LogToConsole(e.Error())
		return nil
	}
	return info
}

func RegInfo() {
	info := ServiceInfo{
		Service: ConfigService,
		Server:  ConfigServer,
		Pid:     os.Getpid(),
		RunPath: os.Args[0],
	}
	err := NsqProducer.Publish(EzTopicReg, info.ToBytes())
	if err != nil {
		LogToConsole(err.Error())
	}
}

func RegApi() {
	for route, handler := range routeHub.DirectRouter {
		dataString := fmt.Sprintf("%s %s %s", ConfigService.AppId, route, handler.Router.Name)
		NsqProducer.Publish(EzTopicRegApi, []byte(dataString))
	}
}
